﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using iWare.Wms.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;

namespace iWare.Wms.Application
{
    /// <summary>
    /// 库存服务
    /// </summary>
    [Route("api/Stock")]
    [ApiDescriptionSettings("仓库基础数据", Name = "Stock", Order = 100)]

    public class WareStockService : IDynamicApiController, ITransient
    {
        private readonly IRepository<WareStock, MasterDbContextLocator> _wareStockRep; //库存仓储

        #region 默认
        /// <summary>
        /// 默认
        /// </summary>
        /// <param name="wareStockRep"></param>
        public WareStockService(
            IRepository<WareStock, MasterDbContextLocator> wareStockRep
        )
        {
            _wareStockRep = wareStockRep;
        }
        #endregion

        /// <summary>
        /// 分页查询库存
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WareStockOutput>> Page([FromQuery] WareStockSearch input)
        {
            var list = await _wareStockRep.DetachedEntities
              .Where(u => u.Status == input.Status)
              .Where(z => z.StockQuantity > new decimal(0.00))
              .Where(!string.IsNullOrEmpty(input.ContainerCode), u => EF.Functions.Like(u.ContainerCode, $"%{input.ContainerCode.Trim()}%"))
              .Where(!string.IsNullOrEmpty(input.LocationCode), u => EF.Functions.Like(u.LocationCode, $"%{input.LocationCode.Trim()}%"))
              .Where(!string.IsNullOrEmpty(input.ProjectCode), u => EF.Functions.Like(u.ProjectCode, $"%{input.ProjectCode.Trim()}%"))
              .Where(!string.IsNullOrEmpty(input.Code), u => EF.Functions.Like(u.Code, $"%{input.Code.Trim()}%"))
              .Where(!string.IsNullOrEmpty(input.SearchBeginTime), u => u.CreatedTime >= DateTime.Parse(input.SearchBeginTime.Trim()) &&
               u.CreatedTime <= DateTime.Parse(input.SearchEndTime.Trim()))
              .OrderBy(PageInputOrder.OrderBuilder<WareStockSearch>(input))
              .ProjectToType<WareStockOutput>()
              .ToADPagedListAsync(input.PageNo, input.PageSize);

            foreach (var item in list.Rows)
            {
                item.BrandName = string.IsNullOrEmpty(item.BrandName) || item.BrandName == "无" ? "" : item.BrandName;
            }
            return list;
        }
    }
}
